<template>
	<view class="chat-page">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content">
				<view class="back-btn" @tap="goBack">
					<text class="iconfont">←</text>
				</view>
				<text class="navbar-title">{{ chat.user.name }}</text>
				<view class="more-btn" @tap="leaveChat">
					<text class="iconfont">离开</text>
				</view>
			</view>
		</view>

		<!-- 聊天区域 -->
		<scroll-view id="scroll-view-content" scroll-y class="chat-container"
			:style="{ paddingTop: (statusBarHeight + 44) + 'px', paddingBottom: inputAreaHeight + 'px' }"
			:scroll-top="scrollTop" scroll-with-animation enable-back-to-top @scroll="onScroll">
			<view id="scroll-view-content-view" class="message-list">
				<!-- 系统消息 -->
				<view v-if="systemMessage" class="system-message">
					<text class="system-message-text">{{ systemMessage }}</text>
				</view>

				<!-- 消息 -->
				<view class="message-item" v-for="(msg, index) in chat.list" :key="msg.id || index" :id="'s' + index">
					<!-- 显示未读消息分隔线 -->
					<p class="un-read-p" v-if="index == chat.readNum && msg.type == 'receive'">
						--------以下是未读消息-------
					</p>

					<!-- 消息时间 -->
					<view class="message-time">
						<text>{{ getTime(msg.time) }}</text>
					</view>

					<!-- 对方消息 -->
					<view v-if="msg.fromId !== currentUserId" class="message-wrapper">
						<image :src="msg.headImg || chat.user.headImg || '/static/images/user-avatar.png'"
							mode="aspectFill" class="avatar"></image>
						<view class="message-content-wrapper">
							<view class="message-bubble other-bubble">
								<!-- 文本消息 -->
								<text class="message-text" v-if="!isImageMessage(msg)">{{ msg.msg }}</text>
								<!-- 图片消息 -->
								<image class="message-image" v-if="isImageMessage(msg)" :src="msg.msg" mode="widthFix" @tap="previewImage(msg.msg)"></image>
							</view>
						</view>
					</view>
					<!-- 我的消息 -->
					<view v-else class="message-wrapper user-wrapper" style="margin-right: 20rpx;">
						<view class="message-content-wrapper user-content">
							<view class="message-bubble user-bubble">
								<!-- 文本消息 -->
								<text class="message-text" v-if="!isImageMessage(msg)">{{ msg.msg }}</text>
								<!-- 图片消息 -->
								<image class="message-image" v-if="isImageMessage(msg)" :src="msg.msg" mode="widthFix" @tap="previewImage(msg.msg)"></image>
							</view>
						</view>
						<image :src="msg.headImg || '/static/images/user-avatar.png'" mode="aspectFill" class="avatar">
						</image>
					</view>
				</view>
				<!-- 占位元素，确保底部输入区不会遮挡内容 -->
				<view class="bottom-placeholder"></view>
			</view>
		</scroll-view>

		<!-- 底部输入区 -->
		<view class="bottom-input">
			<input v-model="inputText" class="message-input" placeholder="输入消息..." confirm-type="send" :focus="focus"
				@confirm="sendMessage" />
			<view class="send-btn" @tap="sendMessage">
				<uniIconsVue type="paperplane-filled" class="iconfont" size="30" @click="sendFile" color="#FFFFFF"
					v-show="inputText && inputText.trim() !== ''"></uniIconsVue>
				<uniIconsVue type="plusempty" class="iconfont" size="30" color="#FFFFFF"
					v-show="!inputText || inputText.trim() === ''" @click="sendFile"></uniIconsVue>
			</view>
		</view>

		<!-- 未登录提示 -->
		<LoginPrompt :is-login="isLogin" prompt-text="请登录后使用聊天功能" @goToLogin="goToLogin" />
	</view>
</template>

<script setup>
	import uniIconsVue from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
	import {
		ref,
		reactive,
		nextTick,
		onMounted,
		onUnmounted
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import userManager from '../../common/utils/user.js'
	import messageCenter from '../../common/utils/messagecenter.js'
	import TimeUtil from '../../common/utils/time.js'
	import {
		generateSnowflakeId
	} from '../../common/utils/Snowflake.js'
	import {
		sendSocketMessage,
		isSocketConnected
	} from '../../common/utils/websocket.js'
	import LoginPrompt from '../../components/LoginPrompt.vue'
	import {
		uploadFile
	} from '@/api/Chat.js'
	const statusBarHeight = ref(0)
	const inputText = ref('')
	const scrollToView = ref('')
	const isLogin = ref(false)
	const currentUserId = ref(null)
	const systemMessage = ref('')
	const scrollTop = ref(0)
	const focus = ref(true)
	const inputAreaHeight = ref(80) // 底部输入区高度（rpx转px后约40px + padding）
	const selectedFilePath = ref('') // 选择的本地文件路径

	// 聊天对象信息（使用 reactive）
	const chat = reactive({
		id: '',
		chatType: '', // 'notification' / 'friend' / 'consultation'
		user: {
			id: '',
			name: '',
			headImg: ''
		},
		lastTime: '',
		readTime: '',
		readNum: 0,
		list: []
	})

	// 获取状态栏高度
	const systemInfo = uni.getSystemInfoSync()
	statusBarHeight.value = systemInfo.statusBarHeight || 0

	// 当前用户信息
	const userInfo = userManager.getUserInfo()
	const my = reactive(userInfo || {})

	// 发送图片
	const sendFile = () => {
		uni.chooseImage({
			count: 1, // 选择图片最大数量
			sizeType: ['compressed'], // 指定是原图还是压缩图
			sourceType: ['album', 'camera'], // 从相册或相机选择
			success: (res) => {
				// 获取选择的图片临时路径
				const tempFilePath = res.tempFilePaths[0];
				selectedFilePath.value = tempFilePath;

				// 上传图片
				uploadImageMessage(tempFilePath);
			},
			fail: (err) => {
				console.error('选择图片失败', err);
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				});
			}
		});
	}

	// 上传图片消息
	const uploadImageMessage = async (tempFilePath) => {
		uni.showLoading({
			title: '上传中...'
		});

		try {
			// 上传图片到服务器
			const imageUrl = await uploadFile(tempFilePath);
			
			// 封装图片消息
			const msg = {
				id: generateSnowflakeId(),
				toId: chat.id,
				fromId: my.userId || my.id,
				name: my.nickName || my.account || '我',
				msg: imageUrl, // 图片URL
				headImg: my.avatarUrl || my.avatar || '/static/images/user-avatar.png',
				time: TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString(),
				type: "send",
				messageType: chat.chatType,
				isImage: true // 标记为图片消息
			}

			// 发送到 WebSocket
			await sendSocketMessage(msg)

			// 添加到本地消息列表
			chat.list.push(msg)

			// 更新最新消息时间和已读数
			chat.lastTime = msg.time
			chat.readNum = chat.list.length

			// 保存到本地存储
			saveChatToStorage()

			// 滚动到底部
			setTimeout(() => {
				scrollToBottom()
			}, 100)
			
			uni.hideLoading();
		} catch (error) {
			console.error('上传图片失败：', error);
			uni.hideLoading();
			uni.showToast({
				title: '图片发送失败',
				icon: 'none'
			});
		}
	}

	// 保存聊天记录到本地存储
	const saveChatToStorage = () => {
		let chatList = uni.getStorageSync("chatList") || []
		const chatIndex = chatList.findIndex(c =>
			c.id === chat.id && c.chatType === chat.chatType
		)

		if (chatIndex !== -1) {
			chatList[chatIndex] = {
				...chat
			}
		} else {
			chatList.unshift({
				...chat
			})
		}

		uni.setStorageSync("chatList", chatList)
		messageCenter.chatList = chatList
	}

	// 预览图片
	const previewImage = (url) => {
		uni.previewImage({
			urls: [url]
		});
	}

	// 创建观察者对象
	const observer = {
		update: () => {
			console.log("聊天页面消息更新")
			// 查找当前聊天
			const chatInfo = messageCenter.chatList.find(c =>
				c.id === chat.id && c.chatType === chat.chatType
			)

			if (chatInfo) {
				// 更新消息列表
				chat.list = [...chatInfo.list]

				// 如果有新消息，标记为已读
				if (chat.list.length > chat.readNum) {
					chat.readNum = chat.list.length
					chat.readTime = TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString()

					// 更新到 messageCenter（会触发未读数量重新计算）
					messageCenter.setReadTime(chat)
				}

				// 延迟滚动到底部，确保新消息DOM已渲染
				setTimeout(() => {
					scrollToBottom()
				}, 100)
			}
		}
	}

	onLoad((options) => {
		// 检查登录状态
		checkLoginStatus()

		// 监听登录状态变化
		uni.$on('loginStatusChanged', handleLoginStatusChanged)

		// 获取传递的参数
		if (options) {
			const chatId = options.id || ''
			const chatType = options.chatType || 'friend'

			// 查找聊天数据
			const chatInfo = messageCenter.chatList.find(c =>
				c.id == chatId && c.chatType == chatType
			)

			if (chatInfo) {
				// 使用已有聊天数据
				Object.assign(chat, chatInfo)
			} else {
				// 创建新的聊天
				chat.id = chatId
				chat.chatType = chatType
				chat.user.id = chatId
				chat.user.name = decodeURIComponent(options.name || '未知用户')
				chat.user.headImg = decodeURIComponent(options.avatar || '/static/images/user-avatar.png')
				chat.list = []
				chat.readNum = 0
			}

			// 获取当前用户ID
			if (userInfo) {
				currentUserId.value = userInfo.userId
			}

			// 添加观察者
			messageCenter.addObserver(observer)

			// 设置页面标题
			uni.setNavigationBarTitle({
				title: chat.user.name
			})

			// 更新已读时间和已读数量
			chat.readTime = TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString()
			chat.readNum = chat.list.length

			// 立即更新到 messageCenter，触发未读数量重新计算
			messageCenter.setReadTime(chat)

			// 滚动到底部
			setTimeout(() => {
				scrollToBottom()
			}, 300)
		}
	})

	onMounted(() => {
		// 计算底部输入区高度
		setTimeout(() => {
			const query = uni.createSelectorQuery()
			query.select('.bottom-input').boundingClientRect()
			query.exec(res => {
				if (res[0]) {
					inputAreaHeight.value = res[0].height + 10 // 加10px缓冲
					console.log('底部输入区高度：', inputAreaHeight.value)
				}
			})
		}, 100)

		// 滚动到底部
		setTimeout(() => {
			scrollToBottom()
		}, 300)
	})

	// 组件卸载时
	onUnmounted(() => {
		// 更新聊天的已读数量
		chat.readNum = chat.list.length

		// 移除观察者
		messageCenter.removeObserver(observer)

		// 更新已读时间
		messageCenter.setReadTime(chat)

		// 取消监听
		uni.$off('loginStatusChanged', handleLoginStatusChanged)
	})

	// 处理登录状态变化
	const handleLoginStatusChanged = (loginStatus) => {
		isLogin.value = loginStatus
		if (!loginStatus) {
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			}, 3000)
		}
	}

	const checkLoginStatus = () => {
		isLogin.value = userManager.checkLogin()
		if (!isLogin.value) {
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			}, 3000)
		} else {
			const userInfo = userManager.getUserInfo()
			if (userInfo) {
				currentUserId.value = userInfo.userId
			}
		}
	}

	// 获取消息时间显示
	function getTime(time) {
		if (TimeUtil.getChatTime) {
			return TimeUtil.getChatTime(time)
		}
		return time
	}

	// 检测消息是否为图片（辅助函数，用于显示时判断）
	function isImageMessage(msg) {
		// 优先使用消息的 isImage 字段
		if (msg.isImage !== undefined) {
			return msg.isImage
		}
		
		// 如果没有 isImage 字段，通过检测 URL 来判断
		const msgContent = msg.msg || ""
		if (!msgContent) return false
		
		const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg']
		const lowerMsg = msgContent.toLowerCase().trim()
		
		// 如果消息内容看起来像URL
		if (lowerMsg.startsWith('http://') || lowerMsg.startsWith('https://')) {
			// 检查URL是否包含图片扩展名
			const hasImageExt = imageExtensions.some(ext => {
				const urlPath = lowerMsg.split('?')[0] // 移除查询参数
				return urlPath.endsWith(ext) || urlPath.includes(ext + '/')
			})
			
			// 检查是否是OSS URL
			const isOssUrl = lowerMsg.includes('oss-cn') || 
			                lowerMsg.includes('aliyuncs.com') ||
			                lowerMsg.includes('/post/') || 
			                lowerMsg.includes('/avatar/') || 
			                lowerMsg.includes('/image')
			
			return hasImageExt || isOssUrl
		}
		
		// 如果不是URL，检查是否包含图片扩展名
		return imageExtensions.some(ext => lowerMsg.includes(ext))
	}

	// 滚动到底部
	function scrollToBottom() {
		nextTick(() => {
			// 添加延迟确保DOM完全渲染
			setTimeout(() => {
				const query = uni.createSelectorQuery()
				query.select("#scroll-view-content").boundingClientRect()
				query.select("#scroll-view-content-view").boundingClientRect()
				query.exec(res => {
					if (res[0] && res[1]) {
						const scrollHeight = res[0].height
						const contentHeight = res[1].height
						if (contentHeight > scrollHeight) {
							// 添加额外偏移量确保最后一条消息完全可见
							// 额外增加100px以确保底部有足够空间
							scrollTop.value = contentHeight - scrollHeight + 100
						}
					}
				})
			}, 50)
		})
	}

	// 处理滚动事件
	const onScroll = (event) => {
		// 可以在这里添加滚动处理逻辑
	}

	const goBack = () => {
		// 更新聊天的已读数量
		chat.readNum = chat.list.length
		messageCenter.setReadTime(chat)
		uni.navigateBack()
	}

	const leaveChat = () => {
		// 更新已读数量和时间
		chat.readNum = chat.list.length
		messageCenter.setReadTime(chat)
	}

	const sendMessage = async () => {
		if (!inputText.value.trim()) return

		// 检查登录状态
		if (!userManager.checkLogin()) {
			showLoginPrompt()
			return
		}

		// 检查WebSocket连接状态
		if (!isSocketConnected()) {
			uni.showToast({
				title: '正在连接服务器...',
				icon: 'loading',
				duration: 1500
			})
			return
		}

		// 封装消息
		const msg = {
			id: generateSnowflakeId(),
			toId: chat.id,
			fromId: my.userId || my.id,
			name: my.nickName || my.account || '我',
			msg: inputText.value,
			headImg: my.avatarUrl || my.avatar || '/static/images/user-avatar.png',
			time: TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString(),
			type: "send",
			messageType: chat.chatType // 添加消息类型
		}

		try {
			// 发送到 WebSocket
			await sendSocketMessage(msg)

			// 添加到本地消息列表
			chat.list.push(msg)

			// 更新最新消息时间和已读数
			chat.lastTime = msg.time
			chat.readNum = chat.list.length

			// 保存到本地存储
			saveChatToStorage()

			// 清空输入框
			inputText.value = ''

			// 设置焦点
			focus.value = false
			nextTick(() => {
				focus.value = true
			})

			// 延迟滚动到底部，确保新消息DOM已渲染
			setTimeout(() => {
				scrollToBottom()
			}, 100)
		} catch (error) {
			console.error('发送消息失败：', error)
			uni.showToast({
				title: '消息发送失败，请检查网络连接',
				icon: 'none',
				duration: 2000
			})
		}
	}

	const showLoginPrompt = () => {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		setTimeout(() => {
			uni.switchTab({
				url: '/pages/mine/mine'
			})
		}, 1000)
	}

	const goToLogin = () => {
		uni.switchTab({
			url: '/pages/mine/mine'
		})
	}
</script>

<style scoped>
	.chat-page {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #F5F5F5;
		position: relative;
		box-sizing: border-box;
		overflow: hidden;
	}

	/* 自定义导航栏 */
	.custom-navbar {
		background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1000;
	}

	.navbar-content {
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
	}

	.back-btn,
	.more-btn {
		width: 64rpx;
		height: 64rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #FFFFFF;
	}

	.navbar-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #FFFFFF;
	}

	/* 系统消息 */
	.system-message {
		text-align: center;
		padding: 20rpx;
	}

	.system-message-text {
		font-size: 24rpx;
		color: #999999;
		background-color: #F5F5F5;
		padding: 10rpx 20rpx;
		border-radius: 10rpx;
	}

	/* 未读消息分隔线 */
	.un-read-p {
		text-align: center;
		font-size: 24rpx;
		color: #999999;
		margin: 20rpx 0;
		padding: 10rpx 0;
	}

	/* 消息时间 */
	.message-time {
		text-align: center;
		margin: 10rpx 0;
	}

	.message-time text {
		font-size: 20rpx;
		color: #999999;
	}

	/* 聊天区域 */
	.chat-container {
		flex: 1;
		overflow-y: auto;
		overflow-x: hidden;
		/* padding-top 和 padding-bottom 通过内联样式动态设置 */
		box-sizing: border-box;
		-webkit-overflow-scrolling: touch;
	}

	.message-list {
		display: flex;
		flex-direction: column;
		padding: 32rpx;
		padding-top: 0;
		padding-bottom: 0;
		min-height: 100%;
		width: 100%;
		box-sizing: border-box;
	}

	.bottom-placeholder {
		height: 120rpx;
		/* 增加高度确保最后一条消息有足够的显示空间 */
	}

	.message-item {
		width: 100%;
		margin-bottom: 20rpx;
	}

	.message-wrapper {
		display: flex;
		align-items: flex-start;
		margin-top: 10rpx;
	}

	.user-wrapper {
		justify-content: flex-end;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		flex-shrink: 0;
	}

	.message-content-wrapper {
		display: flex;
		flex-direction: column;
		max-width: 70%;
		margin: 0 24rpx;
		position: relative;
		top: -10rpx;
	}

	.user-content {
		align-items: flex-end;
	}

	.message-bubble {
		padding: 24rpx;
		border-radius: 24rpx;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
		word-wrap: break-word;
		word-break: break-all;
		display: inline-block;
		max-width: 100%;
	}

	.other-bubble {
		background-color: #FFFFFF;
		border-top-left-radius: 0;
	}

	.user-bubble {
		background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
		border-top-right-radius: 0;
	}

	.user-bubble .message-text {
		color: #FFFFFF;
	}

	.message-text {
		font-size: 28rpx;
		line-height: 1.6;
		color: #333333;
	}

	/* 图片消息样式 */
	.message-image {
		max-width: 400rpx;
		border-radius: 16rpx;
		margin: 0;
		display: block;
		cursor: pointer;
	}

	/* 底部输入区 */
	.bottom-input {
		background-color: #FFFFFF;
		padding: 24rpx 32rpx;
		padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
		border-top: 1px solid #F0F0F0;
		display: flex;
		align-items: center;
		gap: 16rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 999;
		width: 100%;
		box-sizing: border-box;
	}

	.message-input {
		flex: 1;
		background-color: #F5F5F5;
		border-radius: 999rpx;
		padding: 20rpx 32rpx;
		font-size: 28rpx;
	}

	.send-btn {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #89CFF0;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
	}

	/* 未登录提示 */
	.login-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
	}

	.login-prompt {
		background-color: #FFFFFF;
		border-radius: 24rpx;
		padding: 48rpx;
		text-align: center;
		width: 80%;
	}

	.prompt-text {
		display: block;
		font-size: 48rpx;
		margin-bottom: 16rpx;
	}

	.prompt-subtext {
		font-size: 24rpx;
		color: #999999;
	}
</style>